<template>
  <div class="goodsList-container">
    <search-form
      :config-list="searchFormConfig"
      @search="search"
      @reset="reset"
      ref="searchFormRef"
    >
      <template #leftSlot>
        <el-button
          type="primary"
          @click="addGoods"
          v-permissions="['goodslistAdd']"
        >
          新增
        </el-button>
      </template>
      <template #rightSlot>
        <!--右侧的插槽-->
      </template>
    </search-form>
    <el-radio-group
      v-model="activeTab"
      style="margin-bottom: 10px"
      @change="changeTbs"
    >
      <el-radio-button label="自建商品" value="selfGoods" />
      <el-radio-button label="品牌商品" value="brandGoods" />
    </el-radio-group>
    <CustomTable
      :pagination="pagination"
      :table-config="tableConfig"
      @pagination-change="paginationChange"
      @actions-click="actionsClick"
      :key="timer"
    >
      <template #sort="{ row }">
        <el-popover
          placement="right"
          :width="300"
          trigger="click"
          v-if="activeTab !== 'selfGoods' && hasPermission('setSort')"
        >
          <template #reference>
            <span class="sort-span">{{ row.sort }}</span>
          </template>
          <div class="sort-box">
            <span>排序值:</span>
            <el-input
              v-model="sortCount"
              type="number"
              placeholder="请输入排序"
              style="width: 150px"
            />
            <el-button type="primary" size="small" @click="handleSort(row)">
              确定
            </el-button>
          </div>
        </el-popover>
        <span v-else>{{ row.sort }}</span>
      </template>
      <template #setGeneralDiscount="{ row }">
        <el-button
          v-if="row.status !== 1"
          class="btn_item"
          text
          type="primary"
          @click="handleClick('setGeneralDiscount', row)"
        >
          通用折扣
        </el-button>
      </template>
    </CustomTable>
    <Goodsby ref="goodsbyRef" @fetch-data="search" />
  </div>
</template>

<script>
  export default {
    name: 'goodsList',
  }
</script>

<script setup>
  import CustomTable from '@/views/component/CustomTable'
  import SearchForm from '@/views/component/SearchForm' //引入搜索组件
  import Goodsby from '@/views/goods/components/goodsBy.vue'
  import {
    getgoodsList as getList,
    goodsStatusOnOff,
    getBrandList,
    getcateList,
    getFormAdminGoodsList,
    setReturnPointRatio,
    setDiscount,
    setGeneralDiscount,
    updateBrandGoodsSort,
  } from '@/api/goods'
  import { useRouter, useRoute } from 'vue-router'
  import { message } from '@/utils/helper'
  import { hasPermission } from '~/src/utils/permission'
  const router = useRouter()
  const route = useRoute()
  // 搜索参数
  const queryForm = ref({})
  const activeTab = ref('selfGoods')
  const sortCount = ref(0)
  const tableConfig = reactive({
    columns: [
      {
        label: 'ID',
        prop: 'id',
        sortable: false,
        width: 80,
        fixed: 'left',
      },
      {
        label: '产品名',
        prop: 'product_name',
        sortable: false,
        width: 180,
      },
      {
        label: '商品名',
        prop: 'goods_name',
        sortable: false,
        width: 300,
      },
      {
        label: '商品品牌',
        prop: 'brand_name',
        sortable: false,
        width: 110,
      },
      {
        label: '商品分类',
        prop: 'category_name',
        sortable: false,
        width: 110,
        showOverflowTooltip: true,
      },
      {
        label: '返点比例',
        prop: 'return_point_ratio',
        sortable: false,
        width: 100,
      },
      {
        label: '排序',
        prop: 'sort',
        sortable: false,
        width: 60,
        slotName: 'sort',
      },
      {
        label: '状态',
        prop: 'status',
        sortable: false,
        width: 120,
        customType: 'ElTag',
        tagKeyValue: 'statusTag',
      },
      { label: '创建时间', prop: 'create_time', sortable: false, width: 180 },
      {
        label: '操作',
        action: true,
        fixed: 'right',
        actions: [
          {
            fnName: 'down',
            title: '下架',
            type: 'success',
            isTextBtn: true,
            permissionCode: 'goodslistDown', // 权限
            key: 'status',
            showValue: 2,
          },
          {
            fnName: 'setup',
            title: '上架',
            type: 'warning',
            isTextBtn: true,
            permissionCode: 'goodslistSetup', // 权限
            key: 'status',
            showValue: 4,
          },
          {
            fnName: 'view',
            title: '查看',
            type: 'primary',
            isTextBtn: true,
            permissionCode: 'goodslistView', // 权限
            is_admin: false,
          },
          {
            fnName: 'edit',
            title: '编辑',
            type: 'primary',
            isTextBtn: true,
            permissionCode: 'goodslistEdit', // 权限
          },
          {
            fnName: 'lookInfo',
            title: '查看原因',
            type: 'primary',
            isTextBtn: true,
            permissionCode: 'goodslistLookInfo', // 权限
            key: 'status',
            showValue: 3,
          },
          {
            fnName: 'setGeneralDiscount',
            title: '通用折扣',
            type: 'primary',
            isTextBtn: true,
            permissionCode: 'setGeneralDiscount', // 权限
            slotBtnName: 'setGeneralDiscount',
          },
        ],
      },
    ],
    tagConfig: {
      statusTag: {
        1: {
          name: '待审核',
          type: 'success',
        },
        2: {
          name: '上架中',
          type: 'primary',
        },
        3: {
          name: '审核不通过',
          type: 'warning',
        },
        4: {
          name: '已下架',
          type: 'warning',
        },
      },
    },
    list: [],
    listLoading: false,
  })

  const changeTbs = async (val) => {
    if (val === 'selfGoods') {
      tableConfig.columns[tableConfig.columns.length - 1] = {
        label: '操作',
        action: true,
        fixed: 'right',
        actions: [
          {
            fnName: 'down',
            title: '下架',
            type: 'success',
            isTextBtn: true,
            permissionCode: 'goodslistDown', // 权限
            key: 'status',
            showValue: 2,
          },
          {
            fnName: 'setup',
            title: '上架',
            type: 'warning',
            isTextBtn: true,
            permissionCode: 'goodslistSetup', // 权限
            key: 'status',
            showValue: 4,
          },
          {
            fnName: 'view',
            title: '查看',
            type: 'primary',
            isTextBtn: true,
            permissionCode: 'goodslistView', // 权限
            is_admin: false,
          },
          {
            fnName: 'edit',
            title: '编辑',
            type: 'primary',
            isTextBtn: true,
            permissionCode: 'goodslistEdit', // 权限
          },
          {
            fnName: 'lookInfo',
            title: '查看原因',
            type: 'primary',
            isTextBtn: true,
            permissionCode: 'goodslistLookInfo', // 权限
            key: 'status',
            showValue: 3,
          },
          {
            fnName: 'setGeneralDiscount',
            title: '通用折扣',
            type: 'primary',
            isTextBtn: true,
            permissionCode: 'setGeneralDiscount', // 权限
            slotBtnName: 'setGeneralDiscount',
          },
        ],
      }
    } else if (val === 'brandGoods') {
      tableConfig.columns[tableConfig.columns.length - 1] = {
        label: '操作',
        action: true,
        fixed: 'right',
        actions: [
          {
            fnName: 'view',
            title: '查看',
            type: 'primary',
            isTextBtn: true,
            permissionCode: 'goodslistView', // 权限
            is_admin: true,
          },
          {
            fnName: 'returnPointRatio',
            title: '返点比例',
            type: 'success',
            isTextBtn: true,
            permissionCode: 'setReturnPointRatio',
          },
          {
            fnName: 'setDiscount',
            title: '设置规则',
            type: 'warning',
            isTextBtn: true,
            permissionCode: 'setDiscount', // 权限
          },
          {
            fnName: 'setGeneralDiscount',
            title: '通用折扣',
            type: 'primary',
            isTextBtn: true,
            permissionCode: 'setGeneralDiscount', // 权限
          },
        ],
      }
    }
    await queryProject()
    timer.value = new Date().getTime()
  }
  const timer = ref(new Date().getTime())
  //搜索组件配置信息
  const searchFormConfig = reactive({
    config: {
      layoutType: 1, //1:左右布局,2:上下布局
      leftPanelWidth: 0, //控制左边布局控件宽度
    },
    controlList: [
      {
        label: '产品名',
        prop: 'product_name',
        type: 'input',
      },
      {
        label: '商品名',
        prop: 'goods_name',
        type: 'input',
      },
      {
        label: '商品品牌',
        prop: 'brand_id',
        type: 'select',
        list: [],
      },
      {
        label: '商品分类',
        prop: 'category_id',
        type: 'select',
        list: [],
      },
      {
        label: '状态',
        prop: 'status',
        type: 'select',
        list: Object.keys(tableConfig['tagConfig']['statusTag']).reduce(
          (acc, cur) => {
            const { name } = tableConfig['tagConfig']['statusTag'][cur]
            acc.push({ label: name, value: cur })
            return acc
          },
          []
        ),
      },
    ],
  })

  //点击搜索触发
  const search = (form) => {
    console.log(form)
    pagination.page = 1
    queryForm.value = form
    queryProject()
  }

  //列表分页参数
  const pagination = reactive({
    page: 1, //每页条数
    limit: 10, //当前页
    total: 0,
    layout: 'total, sizes, prev, pager, next, jumper',
  })

  //分页控件点击操作
  const paginationChange = (data) => {
    const { val, type } = data
    pagination[type] = val
    queryProject()
  }

  //请求列表数据
  const queryProject = () => {
    tableConfig.listLoading = true
    activeTab.value === 'selfGoods'
      ? getList({
          ...queryForm.value,
          limit: pagination.limit,
          page: pagination.page,
        })
          .then((result) => {
            console.log('result', result)
            tableConfig.list = result.data.data
            tableConfig.listLoading = false
            pagination.total = result.data.total
          })
          .catch(() => {
            tableConfig.listLoading = false
          })
      : getFormAdminGoodsList({
          ...queryForm.value,
          limit: pagination.limit,
          page: pagination.page,
        })
          .then((result) => {
            console.log('result', result)
            tableConfig.list = result.data.data
            tableConfig.listLoading = false
            pagination.total = result.data.total
          })
          .catch(() => {
            tableConfig.listLoading = false
          })
  }
  const goodsbyRef = ref(null)
  //点击表格操作按钮回调
  const actionsClick = (data) => {
    console.log('actionsClick===', data)
    const { type, row, is_admin = false } = data

    const mes = () => {
      ElMessageBox.confirm(
        `确定要${type === 'down' ? '下架' : '上架'}该商品吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        const res = await goodsStatusOnOff({
          id: row.id,
          status: type === 'down' ? 4 : 2,
        })
        if (res.code === 200) {
          message('操作成功')
          queryProject()
        }
      })
    }
    switch (type) {
      case 'down':
        mes()
        break
      case 'setup':
        mes()
        break
      case 'view':
        router.push({
          path: '/goods/goodsApprove',
          query: { id: row.id, action: type, is_admin: is_admin },
        })
        break
      case 'edit':
        router.push({
          path: '/goods/goodsApprove',
          query: { id: row.id, action: type },
        })
        break
      case 'lookInfo':
        ElMessageBox.confirm(
          `${row.audit_remarks || '无审核备注'}`,
          '审核失败原因',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            showCancelButton: false,
            type: 'warning',
          }
        ).then(() => {
          console.log('确定')
        })
        break
      case 'returnPointRatio':
        goodsbyRef.value.open(type, row)
        break
      case 'setDiscount':
        goodsbyRef.value.open(type, row)
        break
      case 'setGeneralDiscount':
        goodsbyRef.value.open(type, row)
        break
    }
  }
  const handleClick = (type, row) => {
    goodsbyRef.value.open(type, row)
  }

  const searchFormRef = ref(null)
  const reset = () => {
    if (!searchFormRef.value) return
    searchFormRef.value.resetFormFields()
    queryProject()
  }

  const init = async () => {
    await queryProject()
  }
  const searchListOptions = ref({
    cateList: [],
    brandList: [],
  })
  const getCateListOption = async () => {
    const { data } = await getcateList()
    searchListOptions.value.cateList = data.data
    const index = searchFormConfig.controlList.findIndex(
      (item) => item.prop === 'category_id'
    )
    searchFormConfig.controlList[index].list =
      searchListOptions.value.cateList.map((item) => ({
        label: item.name,
        value: item.id,
      }))
  }

  const getBrandListOption = async () => {
    const { data } = await getBrandList()
    searchListOptions.value.brandList = data.data
    const index = searchFormConfig.controlList.findIndex(
      (item) => item.prop === 'brand_id'
    )
    searchFormConfig.controlList[index].list =
      searchListOptions.value.brandList.map((item) => ({
        label: item.name,
        value: item.id,
      }))
  }

  const addGoods = () => {
    router.push({
      path: '/goods/goodsApprove',
      query: { action: 'add' },
    })
  }

  const handleSort = async (row) => {
    ElMessageBox.confirm('确定要修改排序吗？越大排越前！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await updateBrandGoodsSort({
        id: row.id,
        sort: sortCount.value,
      })
      message('修改排序成功')
      queryProject()
      sortCount.value = 0
    })
  }
  onMounted(async () => {
    init()
    await getBrandListOption()
    await getCateListOption()
  })

  onActivated(() => {
    if (route.query.repalce) return init()
  })
</script>

<style lang="scss" scoped>
  .sort-span {
    color: #1890ff;
    cursor: pointer;
    text-shadow: #1890ff;
  }
  .sort-box {
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
</style>
